package net.alteiar.ui;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.util.Observable;

import net.alteiar.images.IDrawable;

public class ZoomablePanel<E extends IDrawable> extends BasicPanelImage<E> {
	private static final long serialVersionUID = 1L;

	private double zoomFactor;

	public ZoomablePanel(E img) {
		super(img);
		this.zoomFactor = 1.0;
	}

	public double getZoomFactor() {
		return zoomFactor;
	}

	public Point panelToImage(Point p) {
		int x = (int) (p.x / zoomFactor);
		int y = (int) (p.y / zoomFactor);

		return new Point(x, y);
	}

	public void setZoom(double value) {
		if (value > 0) {
			zoomFactor = value;

			int width = (int) (getImage().getWidth() * zoomFactor);
			int height = (int) (getImage().getHeight() * zoomFactor);

			this.setPreferredSize(new Dimension(width, height));
			this.revalidate();
			this.repaint();
		}
	}

	public void zoomIn(double pas) {
		this.setZoom(zoomFactor + pas);
	}

	public void zoomOut(double pas) {
		zoomIn(-pas);
	}

	@Override
	public void paint(Graphics g) {
		getImage().draw((Graphics2D) g, zoomFactor);
	}

	@Override
	public void update(Observable o, Object arg) {
		// super.update(o, arg);

		int width = (int) (getImage().getWidth() * zoomFactor);
		int height = (int) (getImage().getHeight() * zoomFactor);

		this.setPreferredSize(new Dimension(width, height));
		this.revalidate();
		this.repaint();
	}
}
